import { reactive, onUnmounted } from 'vue';
import { DragState, Cell, Column } from '../types';

// 拖拽管理器
export function useDragDrop(saveState: Function) {
  // 拖拽状态
  const dragState = reactive<DragState>({
    isDragging: false,
    isMovingCells: false,
    dragStartCell: { row: -1, col: -1, x: 0, y: 0 },
    dragPreview: { visible: false, x: 0, y: 0, width: 0, height: 0 },
    draggedCellsData: [],
    dragDataRange: { minRow: 0, maxRow: 0, minCol: 0, maxCol: 0 },
    moveTarget: { row: -1, col: -1 },
    selectedCells: new Set<string>()
  });

  // 存储事件监听器引用，以便清理
  let mouseMoveListener: ((e: MouseEvent) => void) | null = null;

  // 单元格选中状态判断
  const isCellSelected = (row: number, col: number, selectedCells: Set<string>, getCellId: (row: number, col: number) => string): boolean => {
    return selectedCells.has(getCellId(row, col));
  };

  // 行选中状态判断
  const isRowSelected = (row: number, columns: Column[], selectedCells: Set<string>, getCellId: (row: number, col: number) => string): boolean => {
    for (let col = 0; col < columns.length; col++) {
      if (!isCellSelected(row, col, selectedCells, getCellId)) return false;
    }
    return true;
  };

  // 获取单元格ID
  const getCellId = (row: number, col: number): string => `${row}-${col}`;

  // 设置选中单元格
  const setSelectedCells = (cells: Set<string>) => {
    dragState.selectedCells.clear();
    cells.forEach((cell) => dragState.selectedCells.add(cell));
  };

  // 开始拖拽
  const startDrag = (rowIndex: number, colIndex: number, event: MouseEvent) => {
    dragState.dragStartCell = {
      row: rowIndex,
      col: colIndex,
      x: event.clientX,
      y: event.clientY
    };
    dragState.isDragging = true;
  };

  // 开始移动单元格
  const startMoveCells = (selectedCells: Set<string>, tableData: Cell[][]) => {
    dragState.isMovingCells = true;
    dragState.draggedCellsData = [];

    let minRow = Infinity,
      maxRow = -Infinity,
      minCol = Infinity,
      maxCol = -Infinity;

    selectedCells.forEach((cellId) => {
      const [row, col] = cellId.split('-').map(Number);
      minRow = Math.min(minRow, row);
      maxRow = Math.max(maxRow, row);
      minCol = Math.min(minCol, col);
      maxCol = Math.max(maxCol, col);

      if (tableData[row] && tableData[row][col]) {
        dragState.draggedCellsData.push({ row, col, data: tableData[row][col] });
      }
    });

    dragState.dragDataRange = { minRow, maxRow, minCol, maxCol };
  };

  // 显示选中区域拖拽预览
  const showDragPreviewForSelection = (tableWrapper: HTMLElement | null) => {
    if (dragState.draggedCellsData.length > 0 && tableWrapper) {
      const { minRow, maxRow, minCol, maxCol } = dragState.dragDataRange;

      const startCell = document.querySelector(`[data-cell-id="${minRow}-${minCol}"]`) as HTMLElement;
      const endCell = document.querySelector(`[data-cell-id="${maxRow}-${maxCol}"]`) as HTMLElement;

      if (startCell && endCell) {
        const wrapperRect = tableWrapper.getBoundingClientRect();
        const startRect = startCell.getBoundingClientRect();
        const endRect = endCell.getBoundingClientRect();

        // 考虑表格滚动偏移
        dragState.dragPreview.x = startRect.left - wrapperRect.left + tableWrapper.scrollLeft;
        dragState.dragPreview.y = startRect.top - wrapperRect.top + tableWrapper.scrollTop;
        dragState.dragPreview.width = endRect.right - startRect.left;
        dragState.dragPreview.height = endRect.bottom - startRect.top;
        dragState.dragPreview.visible = true;

        dragState.moveTarget = { row: minRow, col: minCol };
        tableWrapper.style.cursor = 'grabbing';
      }
    }
  };

  // 显示拖拽预览
  const showDragPreview = (row: number, col: number, tableData: Cell[][], columns: Column[], tableWrapper: HTMLElement | null) => {
    if (dragState.draggedCellsData.length > 0) {
      const { minRow, maxRow, minCol, maxCol } = dragState.dragDataRange;
      const rowsCount = maxRow - minRow + 1;
      const colsCount = maxCol - minCol + 1;

      const maxTargetRow = Math.max(0, tableData.length - rowsCount);
      const maxTargetCol = Math.max(0, columns.length - colsCount);

      const targetRow = Math.max(0, Math.min(row, maxTargetRow));
      const targetCol = Math.max(0, Math.min(col, maxTargetCol));

      const targetStartCell = document.querySelector(`[data-cell-id="${targetRow}-${targetCol}"]`) as HTMLElement;
      const targetEndCell = document.querySelector(`[data-cell-id="${targetRow + rowsCount - 1}-${targetCol + colsCount - 1}"]`) as HTMLElement;

      if (targetStartCell && targetEndCell && tableWrapper) {
        const wrapperRect = tableWrapper.getBoundingClientRect();
        const startRect = targetStartCell.getBoundingClientRect();
        const endRect = targetEndCell.getBoundingClientRect();

        // 更准确地计算位置，考虑滚动偏移
        dragState.dragPreview.x = startRect.left - wrapperRect.left + tableWrapper.scrollLeft;
        dragState.dragPreview.y = startRect.top - wrapperRect.top + tableWrapper.scrollTop;
        dragState.dragPreview.width = endRect.right - startRect.left;
        dragState.dragPreview.height = endRect.bottom - startRect.top;
        dragState.dragPreview.visible = true;

        dragState.moveTarget = { row: targetRow, col: targetCol };
        tableWrapper.style.cursor = 'grabbing';
      }
    }
  };

  // 高亮目标区域
  const highlightTargetArea = (targetRow: number, targetCol: number, rowsCount: number, colsCount: number) => {
    document.querySelectorAll('.drag-target-highlight').forEach((el) => {
      el.classList.remove('drag-target-highlight');
    });

    for (let r = targetRow; r < targetRow + rowsCount; r++) {
      for (let c = targetCol; c < targetCol + colsCount; c++) {
        const cell = document.querySelector(`[data-cell-id="${r}-${c}"]`);
        if (cell) {
          cell.classList.add('drag-target-highlight');
        }
      }
    }
  };

  // 移动选中单元格
  const moveSelectedCells = (targetRow: number, targetCol: number, tableData: Cell[][]) => {
    if (targetRow < 0 || targetCol < 0 || dragState.draggedCellsData.length === 0) {
      return false;
    }

    const { minRow, maxRow, minCol, maxCol } = dragState.dragDataRange;
    const rowsCount = maxRow - minRow + 1;
    const colsCount = maxCol - minCol + 1;

    if (targetRow === minRow && targetCol === minCol) {
      return true;
    }

    const movedData = dragState.draggedCellsData.map((cellItem) => ({
      ...cellItem.data, // 从data属性中获取Cell数据
      newRow: targetRow + (cellItem.row - minRow),
      newCol: targetCol + (cellItem.col - minCol)
    }));

    try {
      const isOverlap = (row: number, col: number): boolean => {
        return row >= targetRow && row < targetRow + rowsCount && col >= targetCol && col < targetCol + colsCount;
      };
      // 清空被移动的列
      dragState.draggedCellsData.forEach((cellItem) => {
        if (!isOverlap(cellItem.row, cellItem.col) && tableData[cellItem.row] && tableData[cellItem.row][cellItem.col]) {
          tableData[cellItem.row][cellItem.col] = {
            name: '',
            id: '',
            type: '',
            brandId: '',
            customerId: ''
          };
        }
      });
      movedData.forEach((cell: any) => {
        // 从cell对象中提取标准的Cell属性，排除newRow和newCol
        const { newRow, newCol, ...cellData } = cell;
        if (tableData[newRow] && tableData[newRow][newCol]) {
          tableData[newRow][newCol] = {
            ...cellData // 只包含标准的Cell属性
          } as Cell; // 明确类型转换
        }
      });
      return true;
    } catch (error) {
      return false;
    }
  };

  // 处理单元格鼠标按下事件
  const handleCellMouseDown = (
    event: MouseEvent,
    rowIndex: number,
    colIndex: number,
    tableData: Cell[][],
    selectedCells: Set<string>,
    getCellId: (row: number, col: number) => string
  ) => {
    event.preventDefault();

    dragState.dragStartCell = {
      row: rowIndex,
      col: colIndex,
      x: event.clientX,
      y: event.clientY
    };

    // 检查是否在已选中的单元格上开始拖拽
    if (selectedCells.has(getCellId(rowIndex, colIndex)) && selectedCells.size > 0) {
      dragState.isMovingCells = true;

      // 收集要移动的单元格数据
      dragState.draggedCellsData = [];
      let minRow = Infinity,
        maxRow = -Infinity,
        minCol = Infinity,
        maxCol = -Infinity;

      selectedCells.forEach((cellId) => {
        const [row, col] = cellId.split('-').map(Number);
        minRow = Math.min(minRow, row);
        maxRow = Math.max(maxRow, row);
        minCol = Math.min(minCol, col);
        maxCol = Math.max(maxCol, col);

        if (tableData[row] && tableData[row][col]) {
          dragState.draggedCellsData.push({ row, col, data: tableData[row][col] });
        }
      });

      dragState.dragDataRange = { minRow, maxRow, minCol, maxCol };
      return;
    }

    // 普通选择模式
    dragState.isDragging = true;
  };

  // 鼠标移动事件处理
  const handleMouseMove = (
    event: MouseEvent,
    tableData: Cell[][],
    columns: Column[],
    tableWrapper: HTMLElement | null,
    selectedCells: Set<string>,
    getCellId: (row: number, col: number) => string
  ) => {
    // 处理单元格移动
    if (dragState.isMovingCells) {
      const targetElement = document.elementFromPoint(event.clientX, event.clientY);
      const cell = targetElement?.closest('.data-cell');

      if (cell) {
        const cellId = cell.getAttribute('data-cell-id');
        if (cellId) {
          const [row, col] = cellId.split('-').map(Number);
          showDragPreview(row, col, tableData, columns, tableWrapper);
        }
      } else {
        dragState.moveTarget = { row: -1, col: -1 };
        dragState.dragPreview.visible = false;
      }

      if (tableWrapper) {
        tableWrapper.style.cursor = 'grabbing';
      }
      return;
    }

    // 处理框选
    if (!dragState.isDragging) return;
    // 使用 requestAnimationFrame 优化性能
    requestAnimationFrame(() => {
      // 计算选中范围
      const cells = document.querySelectorAll('.data-cell');
      let minRow = dragState.dragStartCell.row;
      let maxRow = dragState.dragStartCell.row;
      let minCol = dragState.dragStartCell.col;
      let maxCol = dragState.dragStartCell.col;

      cells.forEach((cell) => {
        const cellRect = cell.getBoundingClientRect();
        const cellId = cell.getAttribute('data-cell-id');
        if (cellId) {
          const [row, col] = cellId.split('-').map(Number);

          // 检查单元格是否在选择框内
          const isInSelection =
            cellRect.left <= Math.max(event.clientX, dragState.dragStartCell.x) &&
            cellRect.right >= Math.min(event.clientX, dragState.dragStartCell.x) &&
            cellRect.top <= Math.max(event.clientY, dragState.dragStartCell.y) &&
            cellRect.bottom >= Math.min(event.clientY, dragState.dragStartCell.y);

          if (isInSelection) {
            minRow = Math.min(minRow, row);
            maxRow = Math.max(maxRow, row);
            minCol = Math.min(minCol, col);
            maxCol = Math.max(maxCol, col);
          }
        }
      });

      // 清除当前选中
      selectedCells.clear();

      // 更新选中区域
      for (let r = minRow; r <= maxRow; r++) {
        for (let c = minCol; c <= maxCol; c++) {
          selectedCells.add(getCellId(r, c));
        }
      }
    });
  };

  // 添加鼠标移动事件监听器
  const addMouseMoveListener = (handler: (e: MouseEvent) => void) => {
    removeMouseMoveListener(); // 先移除已存在的监听器
    mouseMoveListener = handler;
    document.addEventListener('mousemove', mouseMoveListener);
  };

  // 移除鼠标移动事件监听器
  const removeMouseMoveListener = () => {
    if (mouseMoveListener) {
      document.removeEventListener('mousemove', mouseMoveListener);
      mouseMoveListener = null;
    }
  };

  // 结束拖拽
  const endDrag = (tableWrapper: HTMLElement | null) => {
    dragState.isDragging = false;
    dragState.isMovingCells = false;
    dragState.dragPreview.visible = false;
    dragState.moveTarget = { row: -1, col: -1 };
    dragState.draggedCellsData = [];

    if (tableWrapper) {
      tableWrapper.style.cursor = 'default';
    }

    document.querySelectorAll('.drag-target-highlight').forEach((el) => {
      el.classList.remove('drag-target-highlight');
    });

    const previewElement = document.querySelector('.drag-preview');
    if (previewElement) {
      previewElement.classList.remove('drag-active');
    }

    // 移除鼠标移动监听器
    removeMouseMoveListener();
    saveState();
  };

  // 清空选中
  const clearSelection = (selectedCells: Set<string>) => selectedCells.clear();

  // 选择单元格
  const selectCell = (row: number, col: number, selectedCells: Set<string>, additive: boolean = false) => {
    if (!additive) clearSelection(selectedCells);
    selectedCells.add(getCellId(row, col));
  };

  // 选择范围
  const selectRange = (startRow: number, startCol: number, endRow: number, endCol: number, selectedCells: Set<string>, additive: boolean = false) => {
    if (!additive) clearSelection(selectedCells);

    const minRow = Math.min(startRow, endRow);
    const maxRow = Math.max(startRow, endRow);
    const minCol = Math.min(startCol, endCol);
    const maxCol = Math.max(startCol, endCol);

    for (let r = minRow; r <= maxRow; r++) {
      for (let c = minCol; c <= maxCol; c++) {
        selectedCells.add(getCellId(r, c));
      }
    }
  };

  // 判断是否为拖拽目标区域
  const isDragOver = (row: number, col: number): boolean => {
    if (!dragState.isMovingCells || dragState.moveTarget.row === -1) return false;
    const { minRow, maxRow, minCol, maxCol } = dragState.dragDataRange;
    const rowsCount = maxRow - minRow + 1;
    const colsCount = maxCol - minCol + 1;

    return (
      row >= dragState.moveTarget.row &&
      row < dragState.moveTarget.row + rowsCount &&
      col >= dragState.moveTarget.col &&
      col < dragState.moveTarget.col + colsCount
    );
  };

  // 获取预览单元格的样式
  const getPreviewCellStyle = (cellData: { row: number; col: number; data: Cell }) => {
    // 缓存计算结果
    const { minRow, maxRow, minCol, maxCol } = dragState.dragDataRange;
    const rowsCount = maxRow - minRow + 1;
    const colsCount = maxCol - minCol + 1;

    const rowOffset = cellData.row - minRow;
    const colOffset = cellData.col - minCol;

    const cellWidth = 100 / colsCount;
    const cellHeight = 100 / rowsCount;

    return {
      position: 'absolute',
      left: `${colOffset * cellWidth}%`,
      top: `${rowOffset * cellHeight}%`,
      width: `${cellWidth}%`,
      height: `${cellHeight}%`,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      fontSize: '14px',
      padding: '4px',
      boxSizing: 'border-box',
      border: '1px solid rgba(255, 255, 255, 0.3)',
      overflow: 'hidden',
      textOverflow: 'ellipsis',
      whiteSpace: 'nowrap',
      transition: 'all 0.1s ease'
    };
  };

  // 清理函数 - 在组件销毁时调用
  const cleanup = () => {
    // 移除所有事件监听器
    removeMouseMoveListener();

    // 清理高亮元素
    document.querySelectorAll('.drag-target-highlight').forEach((el) => {
      el.classList.remove('drag-target-highlight');
    });

    // 清理预览元素
    const previewElement = document.querySelector('.drag-preview');
    if (previewElement) {
      previewElement.classList.remove('drag-active');
    }
  };

  return {
    dragState,
    isDragOver,
    setSelectedCells,
    getPreviewCellStyle,
    getCellId,
    startDrag,
    handleMouseMove,
    handleCellMouseDown,
    startMoveCells,
    showDragPreviewForSelection,
    highlightTargetArea,
    moveSelectedCells,
    endDrag,
    clearSelection,
    selectCell,
    selectRange,
    isRowSelected,
    isCellSelected,
    addMouseMoveListener, // 添加鼠标移动监听器
    removeMouseMoveListener, // 移除鼠标移动监听器
    cleanup // 导出清理函数
  };
}
